﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ucntemaxp.DB;
using System.Linq.Expressions;

namespace ucntemaxp.Ctr
{
    class CtrRabat
    {
        private DB.Dm74_1Entities DBCon;
        public CtrRabat()
        {
             DBCon = new DB.Dm74_1Entities();
        }

        public void opretRabat(string navn, int rabatværdi)
        {
           
            try
            {
                DBCon.Rabats.AddObject(new Rabat()
                {
                    Navn = navn,
                    RabatVærdi = rabatværdi,
                });
                DBCon.SaveChanges();
            }
            catch (Exception)
            {
                
                throw;
            }
            

        }

        public void removeRabat(int id)
        {
            DBCon.Rabats.DeleteObject(new Rabat()
            {
                Rabatid = id
            });
        }

        public void updateRabat(int id, string navn, int rabatværdi)
        {
            try
            {
                Rabat r = DBCon.Rabats.First(i => i.Rabatid == id);
                r.Navn = navn;
                r.RabatVærdi = rabatværdi;
                DBCon.SaveChanges();
            }
            catch (Exception ex)
            {
              
                throw ex;
            }
        }

        public Rabat findRabat(int id)
        {
            try
            {
                Rabat r = DBCon.Rabats.First(i => i.Rabatid == id);
                return r;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public List<Rabat> alleRabatter()
        {
            List<Rabat> list = new List<Rabat>();
            int count = 1;
            while(count <= DBCon.Rabats.Count())
            {
                list.Add(DBCon.Rabats.First(i => i.Rabatid == count));
                count++;
            }
            return list;
        }

        public Rabat findRabatNavn(string navn)
        {
            try
            {
                Rabat r = DBCon.Rabats.First(i => i.Navn.Equals(navn));
                return r;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public void Update(Action<Rabat> updateStatement, Expression<Func<Rabat, bool>> where)
        {
            // get your object context & objectset, cast to IQueryable<T>
            var table = (IQueryable<Rabat>)DBCon.CreateObjectSet<Rabat>();

            // filter with the Expression
            var items = table.Where(where);

            // perform the Action on each item
            foreach (var item in items)
            {
                updateStatement(item);  
            }

            // save changes.
        }

    }
}
